package ve.com.wayoyo.wuml_case;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

import ve.com.wayoyo.wuml_case.Bluetooth.ConnectThread;
import ve.com.wayoyo.wuml_case.Bluetooth.ThreadServer;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;

public class Compartir extends Activity {
	
	private static final int REQUEST_ENABLE_BT = 1;
	private ArrayList<BluetoothDevice> mArrayAdapter;
	private String[] _array_spinner;
	private Spinner spListaProyecto;
	private String[] values;
	public static Boolean _estatus;
	private ArrayList<View> listView;
	private CheckBox cb_seleccionarTodos;
	private LinearLayout ly_global;
	private LinearLayout ly_temp;
	private LinearLayout ly_Buscando;

	private ProgressBar mProgress;
	private int mProgressStatus = 0;
	private Handler mHandler = new Handler();
	private Thread buscando;
	private int control;

	private String root;
		
	public Compartir() {
		_estatus = false;	
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_compartir);
		this.mArrayAdapter = new ArrayList<BluetoothDevice>();
		control = 0 ;
		
		
		this.resetSpProyecto();
		this.setIniProyecto();
		this.resetspListFiles(UserPref.getInstancia().getNombreProyecto());			
	}
	
	protected void confirmacionRecibido(String texto) {
		Alert.show(texto, Compartir.this, Alert.OK);
	}

	private void resetspListFiles(final String nombreProyecto) {
		ListView listView = (ListView) findViewById(R.id.listView1);
		CargaListaArchivos(nombreProyecto);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1, values);

		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				root = Environment.getExternalStorageDirectory() + "//WUML//"
						+ nombreProyecto + "//DIAGRAMAS//" + values[position];

				DiagramSelected();
			}
		});
	}

	private void CargaListaArchivos(String nombreProyecto) {
		File mPath = new File(Environment.getExternalStorageDirectory()
				+ "//WUML//" + nombreProyecto + "//DIAGRAMAS");
		try {
			mPath.mkdirs();
		} catch (SecurityException e) {
			// Log.e(TAG, "unable to write on the sd card " + e.toString());
		}
		if (mPath.exists()) {
			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String filename) {
					File sel = new File(dir, filename);
					return (filename.contains(".wuml"));
					// return true;
				}
			};
			values = mPath.list(filter);
		} else {

			values = new String[0];
		}
	}

	private void setIniProyecto() {
		for (int i = 0; i < _array_spinner.length; i++) {
			if (_array_spinner[i].equals(UserPref.getInstancia()
					.getNombreProyecto())) {
				spListaProyecto.setSelection(i);
				i = _array_spinner.length;
			}
		}
	}

	private void resetSpProyecto() {
		spListaProyecto = (Spinner) findViewById(R.id.sp_proyectos);
		this.CargaListaProyecto();
		if (_array_spinner.length == 0) {
			_array_spinner = new String[] { "No Existen Proyectos Registrados" };
		}
		ArrayAdapter<?> sp_adapter = new ArrayAdapter<Object>(this,
				android.R.layout.simple_spinner_item, _array_spinner);
		spListaProyecto
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						if (_array_spinner[position]
								.equals("No Existen Proyectos Registrados")) {

						} else if (!(_array_spinner[position].equals(UserPref
								.getInstancia().getNombreProyecto()))) {
							Alert.show("El proyecto activo es: "
									+ _array_spinner[position], Compartir.this,
									Alert.OK);
							UserPref.getInstancia().setNombreProyecto(
									_array_spinner[position]);

							Compartir.this
									.resetspListFiles(_array_spinner[position]);
							try {
								UserPref.getInstancia().guardarUserPref();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}

					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
		spListaProyecto.setAdapter(sp_adapter);
	}

	private void CargaListaProyecto() {
		File mPath = new File(Environment.getExternalStorageDirectory()
				+ "//WUML");
		try {
			mPath.mkdirs();

		} catch (SecurityException e) {
			// Log.e(TAG, "unable to write on the sd card " + e.toString());
		}
		if (mPath.exists()) {
			FilenameFilter filter = new FilenameFilter() {
				public boolean accept(File dir, String filename) {
					File sel = new File(dir, filename);
					return (sel.isDirectory());
					// return true;
				}
			};
			_array_spinner = mPath.list(filter);
		} else {

			_array_spinner = new String[0];
		}
	}

	public void ActivarBT(View view) {
		ImageButton imbt = (ImageButton) findViewById(R.id.button1);
		ImageButton logo = (ImageButton) findViewById(R.id.button2);
		RelativeLayout ly = (RelativeLayout) findViewById(R.id.linearLayout1);
		RelativeLayout ly_fondo = (RelativeLayout) findViewById(R.id.fondoly);
		if (_estatus) {
			imbt.setImageResource(R.drawable.botonactivarvisible);
			logo.setImageResource(R.drawable.iconobluetoothinactivo);
			_estatus = false;
			ly.setVisibility(RelativeLayout.VISIBLE);
			ly_fondo.setBackgroundResource(R.drawable.hoja);
		} else {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivityForResult(discoverableIntent, 0);
			
//			ly_fondo.setBackgroundResource(R.drawable.asociacion_directa);
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data){		
		if (resultCode!=0){
			ImageButton imbt = (ImageButton) findViewById(R.id.button1);
			ImageButton logo = (ImageButton) findViewById(R.id.button2);
			RelativeLayout ly = (RelativeLayout) findViewById(R.id.linearLayout1);
			Handler _mHandler = new Handler()
			{
			    public void handleMessage(Message msg)
			    {
			    
			       Compartir.this.confirmacionRecibido(msg.getData().getString(null));
			    }
			};
			ThreadServer client = new ThreadServer(_mHandler);
			client.start();
			imbt.setImageResource(R.drawable.botondesactivarvisible);
			logo.setImageResource(R.drawable.iconobluetoothactivo);
			_estatus = true;
			ly.setVisibility(RelativeLayout.GONE);
		}
	}
	
	
	public void DiagramSelected() {
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		if (mBluetoothAdapter == null) {

			// Device does not support Bluetooth
		} else {
			if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			}

			enviar(root);

		}
	}

	// Create a BroadcastReceiver for ACTION_FOUND
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			// When discovery finds a device
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// Get the BluetoothDevice object from the Intent
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (!mArrayAdapter.contains(device)) {
					mArrayAdapter.add(device);
				}

			} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
				ly_Buscando.setVisibility(LinearLayout.VISIBLE);
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				ly_Buscando.setVisibility(LinearLayout.GONE);
			}
		}

	};

	public void scanear() {
		// Register the BroadcastReceiver
		// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, filter); // Don't forget to unregister
		// during onDestroy
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		registerReceiver(mReceiver, filter);
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiver, filter);

		// Iniciamos el scaner
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		mBluetoothAdapter.startDiscovery();
		
	}
	
	protected void enviar(final String root) {
		scanear();
		ly_global = new LinearLayout(this);
		GetListDevices();
		final CountDownTimer timer = new CountDownTimer(150000, 1000) {

			public void onTick(long millisUntilFinished) {
				if (mArrayAdapter.size() > listView.size()) {
					Compartir.this.recalcDevices();
				}

			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				ly_global.removeAllViews();
				
			}
		}.start();

		new AlertDialog.Builder(this)
				.setIcon(R.drawable.warning)
				.setTitle("Advertencia")
				.setView(ly_global)
				// .setMessage(_mensaje)
				.setPositiveButton("Aceptar",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								File diagramaFile = new File(root);
								InputStream fis;
								BufferedReader br;
								String line;
								String diagrama = "";
								try {
									fis = new FileInputStream(diagramaFile);
									br = new BufferedReader(
											new InputStreamReader(fis, Charset
													.forName("UTF-8")));
									while ((line = br.readLine()) != null) {
										diagrama += "\n" + line;
									}
								} catch (Exception e) {
									System.out.println(e.getMessage());
								}
								for (int value : Compartir.this.getSelectedDevice()) {										
									ConnectThread server = new ConnectThread(
											mArrayAdapter.get(value), diagrama);
									server.start();									
								}
								
							}
						})
				.setNegativeButton("Cancelar",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								mArrayAdapter.clear();
								listView.clear();
							}
						}).show();

	}

	protected int[] getSelectedDevice() {
		int i = 0;
		int size = 0;
		for (View value : listView) {
			if (((CheckBox) value).isChecked()) {
				size++;
			}
			i++;
		}
		int[] ret = new int[size];
		int control = 0;
		i=0;
		for (View value : listView) {
			if (((CheckBox) value).isChecked()) {
				ret[control]=i;
				control++;
			}
			i++;
		}
		return ret;
	}

	private void getBuscando(){
//		if (ly_Buscando.getVisibility()) {
			ly_Buscando = new LinearLayout(getApplicationContext());
			mProgress = new ProgressBar(getApplicationContext(), null, android.R.attr.progressBarStyleSmall);			
			buscando = new Thread(new Runnable() {
				public void run() {
					while (mProgressStatus < 100) {
						// Update the progress bar
						mProgressStatus = control;
						
						mHandler.post(new Runnable() {
							public void run() {
								mProgress.setProgress(mProgressStatus);
							}
						});
					}
				}

			});
			buscando.start();
			ly_Buscando.addView(mProgress);
			ly_global.addView(ly_Buscando);
			ly_Buscando.setVisibility(LinearLayout.GONE);
//		} else{
//			ly_Buscando.setVisibility(LinearLayout.VISIBLE);
//			
//		}
	}
	
	private void GetListDevices() {
		ly_global.setOrientation(LinearLayout.VERTICAL);
		getBuscando();		
		cb_seleccionarTodos = new CheckBox(this);
		cb_seleccionarTodos.setText("Seleccionar Todos");
		cb_seleccionarTodos
				.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							Compartir.this.CheckAll();
						} else {
						}
					}
				});
		ly_global.addView(cb_seleccionarTodos);
		ScrollView sv = new ScrollView(this);
		ly_temp = new LinearLayout(this);
		ly_temp.setOrientation(LinearLayout.VERTICAL);
		ly_temp.setPadding(50, 0, 0, 0);
		sv.addView(ly_temp, new LayoutParams(400, 450));
		setListDevices(ly_temp);
		ly_global.addView(sv);
	}

	protected void CheckAll() {
		for (View device : listView) {
			((CheckBox) device).setChecked(true);
		}
	}
	
	private void setListDevices(LinearLayout ly_global) {
		int i = 1;
		listView = new ArrayList<View>();
		for (BluetoothDevice device : mArrayAdapter) {
			final CheckBox cb_act = new CheckBox(this);
			if (device.getName() != null)
				cb_act.setText(device.getName());
			else
				cb_act.setText(device.getAddress());
			cb_act.setId(i);
			ly_global.addView(cb_act);
			listView.add(cb_act);
			cb_act.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					isAllCheck(cb_act);
				}
			});
			i++;
		}
	}

	protected void recalcDevices() {
		BluetoothDevice device = null;
		for (int i = listView.size(); i < mArrayAdapter.size(); i++) {
			device = mArrayAdapter.get(i);
			final CheckBox cb_act = new CheckBox(this);
			if (device.getName() != null)
				cb_act.setText(device.getName());
			else
				cb_act.setText(device.getAddress());
			cb_act.setId(listView.size() + 1);
			ly_temp.addView(cb_act);
			listView.add(cb_act);
			cb_act.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					isAllCheck(cb_act);
				}
			});
		}
	}
	
	public void isAllCheck(CheckBox cb_act) {
		Boolean flag = true;
		for (View device : listView) {
			if (!(((CheckBox) device).isChecked())) {
				flag = false;
				break;
			}
		}
		this.cb_seleccionarTodos.setChecked(flag);
	}
}